package cn.yx.framework.view;

import cn.yx.framework.error.ControllerExceptionHandler;
import cn.yx.framework.exception.BasicException;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017-02-10.
 */
public class OutViewer {
    private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);
    private static final String TEMPLATE_HTML_DEBUG = "<!DOCTYPE html><html lang=\"zh\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1, UserModel-scalable=no\"><meta name=\"format-detection\" content=\"telephone=no\"><title>%s</title><style>body {background-image:url(\"\");} h3 {text-align:center;color:#9A8383;}.copyright{position:fixed;bottom:0;font-size:12px;color:#ccc;text-align:center;width: 100%%;} .copyright a{text-decoration:none;color:#ccc;}</style></head><body><div><h3>%s</h3></div><div><h3>查看堆栈:</h3><div><pre>%s</pre></div></div><div class=\"copyright\">Power by <a href=\"http://ucox.cn\">ucox.cn</a></div></body></html>";
    private static final String TEMPLATE_HTML_RELEASE = "<!DOCTYPE html><html lang=\'zh\'><head><meta charset=\'UTF-8\'><meta name=\'viewport\' content=\'initial-scale=1, maximum-scale=1, UserModel-scalable=no\'><meta name=\'format-detection\' content=\'telephone=no\'><title>%s</title><style>body {background-image:url(\'\');}h3 {text-align:center;color:#9A8383;} .copyright{position:fixed;bottom:0;font-size:12px;color:#ccc;text-align:center;width:100%%;} .copyright a{text-decoration:none;color:#ccc;}</style></head><body><div><h3>%s</h3></div><div class=\'copyright\'>Power by <a href=\'http://ucox.cn\'>ucox.cn</a></div></body></html>";

    public OutViewer() {
    }

    public static boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")) || "application/json".equalsIgnoreCase(request.getHeader("Accept"));
    }

    public static void out(HttpServletRequest request, HttpServletResponse response, Map<String, Object> model) {
        if (isAjax(request)) {
            json(response, model);
        }

        html(response, model);
    }

    public static void json(HttpServletResponse response, Map<String, Object> model) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        try {
            writer = response.getWriter();
            if (null == writer) {
                return;
            }

            writer.write(JSON.toJSONString(model));
        } catch (IOException var7) {
            logger.error("*", var7);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }

        }

    }

    public static String getMessage(HttpStatus status) {
        switch (status.value()) {
            case 403:
                return "请求未授权";
            case 404:
                return "页面未找到";
            case 405:
                return "请求方法不允许";
            case 500:
                return "服务器错误";
            default:
                return "请求失败";
        }
    }

    public static void html(HttpServletResponse response, Map<String, Object> model) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");

        try {
            writer = response.getWriter();
            if (null == writer) {
                return;
            }

            if (logger.isDebugEnabled()) {
                writer.write(String.format("<!DOCTYPE html><html lang=\"zh\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1, UserModel-scalable=no\"><meta name=\"format-detection\" content=\"telephone=no\"><title>%s</title><style>body {background-image:url(\"\");} h3 {text-align:center;color:#9A8383;}.copyright{position:fixed;bottom:0;font-size:12px;color:#ccc;text-align:center;width: 100%%;} .copyright a{text-decoration:none;color:#ccc;}</style></head><body><div><h3>%s</h3></div><div><h3>查看堆栈:</h3><div><pre>%s</pre></div></div><div class=\"copyright\">Power by <a href=\"http://ucox.cn\">ucox.cn</a></div></body></html>", new Object[]{model.get("code"), model.get("msg"), BasicException.getFormatTrace(model.get("trace"))}));
            } else {
                writer.write(String.format("<!DOCTYPE html><html lang=\'zh\'><head><meta charset=\'UTF-8\'><meta name=\'viewport\' content=\'initial-scale=1, maximum-scale=1, UserModel-scalable=no\'><meta name=\'format-detection\' content=\'telephone=no\'><title>%s</title><style>body {background-image:url(\'\');}h3 {text-align:center;color:#9A8383;} .copyright{position:fixed;bottom:0;font-size:12px;color:#ccc;text-align:center;width:100%%;} .copyright a{text-decoration:none;color:#ccc;}</style></head><body><div><h3>%s</h3></div><div class=\'copyright\'>Power by <a href=\'http://ucox.cn\'>ucox.cn</a></div></body></html>", new Object[]{model.get("code"), model.get("msg")}));
            }
        } catch (IOException var7) {
            logger.error("*", var7);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }

        }

    }

    public static Map<String, Object> extractException(final Exception ex) {
        return (Map) (ex instanceof BasicException ? ((BasicException) ex).getReport() : (ex instanceof IllegalArgumentException ? new HashMap() {
            {
                this.put("code", Integer.valueOf(5001));
                this.put("msg", "输入参数有误");
                this.put("time", new Date());
                this.put("data", ex.getCause());
                this.put("trace", ex.getStackTrace());
            }
        } : (ex instanceof MethodArgumentTypeMismatchException ? new HashMap() {
            {
                this.put("code", Integer.valueOf(5001));
                this.put("msg", "请求方法参数类型不匹配");
                this.put("time", new Date());
                this.put("data", ex.getCause());
                this.put("trace", ex.getStackTrace());
            }
        } : (!(ex instanceof MethodArgumentConversionNotSupportedException) && !(ex instanceof HttpMessageNotReadableException) ? (ex instanceof HttpRequestMethodNotSupportedException ? new HashMap() {
            {
                this.put("code", Integer.valueOf(5405));
                this.put("msg", "请求方法不支持");
                this.put("time", new Date());
                this.put("data", ex.getCause());
                this.put("trace", ex.getStackTrace());
            }
        } : (ex instanceof HttpMediaTypeNotAcceptableException ? new HashMap() {
            {
                this.put("code", Integer.valueOf(4006));
                this.put("msg", "响应数据类型不支持");
                this.put("time", new Date());
                this.put("data", ex.getCause());
                this.put("trace", ex.getStackTrace());
            }
        } : (ex instanceof HttpMediaTypeNotSupportedException ? new HashMap() {
            {
                this.put("code", Integer.valueOf(4001));
                this.put("msg", "请求参数类型不支持");
                this.put("time", new Date());
                this.put("data", ex.getCause());
                this.put("trace", ex.getStackTrace());
            }
        } : (ex instanceof RuntimeException ? new HashMap() {
            {
                this.put("code", Integer.valueOf(5002));
                this.put("msg", "运行时错误");
                this.put("time", new Date());
                this.put("data", ex.getCause());
                this.put("trace", ex.getStackTrace());
            }
        } : new HashMap() {
            {
                this.put("code", Integer.valueOf(5000));
                this.put("msg", "系统错误");
                this.put("time", new Date());
                this.put("data", ex.getCause());
                this.put("trace", ex.getStackTrace());
            }
        })))) : new HashMap() {
            {
                this.put("code", Integer.valueOf(4002));
                this.put("msg", "请求方法参数转换错误");
                this.put("time", new Date());
                this.put("data", ex.getCause());
                this.put("trace", ex.getStackTrace());
            }
        }))));
    }
}
